package com.renwei.yunlong.adapter;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.DisplayUserInfoActivity;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.RoundView;

import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * Project :  yunaandroid.
 * Package name: com.renwei.yunlong.adapter
 * Created by :  Benjamin.
 * Created time: 2017/11/30 9:20
 * Changed by :  Benjamin.
 * Changed time: 2017/11/30 9:20
 * Class description:
 */
public class SortContactAdapter extends BaseAdapter implements SectionIndexer {
    private String companyType;
    private List<Contact> contactList;
    private Context mContext;
    private int type = 0;// TODO: 2017/12/8 0 代表默认联系人列表  1代表复选框列表
    private boolean isOutFriend = false;// TODO: 2017/12/10 判断是否好友企业好友

    public SortContactAdapter(Context mContext, int type, String companyType, List<Contact> contactList) {
        this.companyType = companyType;
        this.type = type;
        this.mContext = mContext;
        this.contactList = contactList;
    }

    public SortContactAdapter(Context mContext, int type, String companyType, List<Contact> contactList, boolean out) {
        this.companyType = companyType;
        this.type = type;
        this.mContext = mContext;
        this.contactList = contactList;
        this.isOutFriend = out;
    }

    public void refresh(List<Contact> contactList) {
        this.contactList = contactList;
        this.notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return UtilList.getCount(contactList);
    }

    @Override
    public Contact getItem(int position) {
        return contactList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View view, ViewGroup arg2) {
        ViewHolder viewHolder = null;
        final Contact item = contactList.get(position);
        if (view == null) {
            if (type == 0) {
                viewHolder = new ViewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.item_contact, null);
                viewHolder.tvTitle = view.findViewById(R.id.tv_name);
                viewHolder.tvLetter = view.findViewById(R.id.tv_letter);
                viewHolder.tvDepartment = view.findViewById(R.id.tv_department);
                viewHolder.tvGroup = view.findViewById(R.id.tv_group);
                viewHolder.ivCall = view.findViewById(R.id.iv_call);
                viewHolder.ivMsg = view.findViewById(R.id.iv_msg);
                viewHolder.rvPic = view.findViewById(R.id.rv_header);
                viewHolder.rlParent = view.findViewById(R.id.contact_parent);
                view.setTag(viewHolder);
            } else {
                viewHolder = new ViewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.item_contact_check, null);
                viewHolder.tvTitle = view.findViewById(R.id.tv_name);
                viewHolder.tvLetter = view.findViewById(R.id.tv_letter);
                viewHolder.tvDepartment = view.findViewById(R.id.tv_department);
                viewHolder.tvGroup = view.findViewById(R.id.tv_group);
                viewHolder.rvPic = view.findViewById(R.id.rv_header);
                viewHolder.rlParent = view.findViewById(R.id.contact_parent);
                viewHolder.ivCheck = view.findViewById(R.id.iv_check);
                view.setTag(viewHolder);
            }
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        int section = getSectionForPosition(position);
        if (position == getPositionForSection(section)) {
            viewHolder.tvLetter.setVisibility(View.VISIBLE);
            viewHolder.tvLetter.setText(item.getLetter());

        } else {
            viewHolder.tvLetter.setVisibility(View.GONE);
        }
        final String name = "".equals(StringUtils.value(item.getName())) ? StringUtils.value(item.getEmployeeName()) : StringUtils.value(item.getName());
        viewHolder.tvTitle.setText(name);
        if (TextUtils.isEmpty(StringUtils.value(item.getDepartmentName()))) {
            viewHolder.tvDepartment.setText("未分配部门");
        } else {
            viewHolder.tvDepartment.setText(StringUtils.value(item.getDepartmentName()));
        }
        if (TextUtils.isEmpty(StringUtils.value(item.getGroupName()))) {
            viewHolder.tvGroup.setText("/未分配职能");
        } else {
            viewHolder.tvGroup.setText("/" + item.getGroupName());
        }
        String avatar = "";// TODO: 2017/12/10 防止第二次点击的时候再次添加前缀导致图片不显示
        if (!StringUtils.value(item.getAvatar()).startsWith("http")) {
            if ("1".equals(companyType)) {
                avatar = Api.$().OWNER_FILE_URL + StringUtils.value(item.getAvatar());

            } else if ("2".equals(companyType)) {
                avatar = Api.$().SERVICE_FILE_URL + StringUtils.value(item.getAvatar());
            }
        } else {
            avatar = item.getAvatar();
        }
        Glide.with(mContext).load(avatar).placeholder(R.mipmap.icon_header_default).error(R.mipmap.icon_header_default).into(viewHolder.rvPic);
        if (type == 0) {// TODO: 2017/12/8 从联系人模块条转过来
            viewHolder.ivMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", "1".equals(companyType) ? Api.$().OWNER_FILE_URL + item.getAvatar() : Api.$().SERVICE_FILE_URL + item.getAvatar());
                    RongIM.getInstance().startConversation(mContext, Conversation.ConversationType.PRIVATE,
                            item.getEmployeeId(), name, bundle);
                }
            });
            viewHolder.ivCall.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + StringUtils.value(item.getMobilePhone())));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                }
            });
            viewHolder.rlParent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isOutFriend) {
                        DisplayUserInfoActivity.OpenActivity(mContext, StringUtils.value(item.getEmployeeId()), "1");
                    } else {
                        DisplayUserInfoActivity.OpenActivity(mContext, StringUtils.value(item.getEmployeeId()), "");
                    }
                }
            });
        } else {// TODO: 2017/12/8 从消息模块跳转过来 从群组成员模块跳转过里啊
            if (AppHelper.hasGroupMember(item))// TODO: 2017/12/10 代表当前已经是群组成员了
            {
                viewHolder.ivCheck.setImageResource(R.mipmap.check01);
                viewHolder.rlParent.setOnClickListener(null);
            } else {
                if (AppHelper.hasContact(item)) {// TODO: 2017/12/10 判断当前条目是否选中状态
                    viewHolder.ivCheck.setImageResource(R.mipmap.check02);
                } else {
                    viewHolder.ivCheck.setImageResource(R.mipmap.check03);
                }
                final String finalAvatar = avatar;//为了让好友企业联系人也能在底部显示头像
                viewHolder.rlParent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // TODO: 2017/12/8 点击条目添加当前条目到群组列表中
                        item.setAvatar(finalAvatar);
                        if (isOutFriend) {
                            if ("1".equals(companyType)){
                                item.setSourceFlag("0");
                            }else{
                                item.setSourceFlag("1");
                            }
                        }
                        AppHelper.setCheck(item);
                    }
                });
            }

        }

        return view;

    }

    @Override
    public int getSectionForPosition(int position) {
        return contactList.get(position).getLetter().charAt(0);
    }

    @Override
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = contactList.get(i).getLetter();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }


    @Override
    public Object[] getSections() {
        return null;
    }

    final static class ViewHolder {
        TextView tvLetter;
        TextView tvDepartment;
        TextView tvGroup;
        TextView tvTitle;
        RoundView rvPic;
        ImageView ivCall;
        ImageView ivMsg;
        ImageView ivCheck;
        RelativeLayout rlParent;

    }


}